package com.acme.bankapp.domain.email;

import java.util.ArrayList;
import java.util.List;

public class Queue {
	private List<Email> queue = new ArrayList<>();
	private int maxSize;
	private volatile boolean isClosed = false;
	
	public Queue(int maxSize) {
		this.maxSize = maxSize;
	}
	
	public Email getItem() {
		synchronized (queue) {
			while (queue.isEmpty() && !isClosed) {
				try {
					queue.wait();
				} catch (InterruptedException ignore) { }
			}
			
			if (!queue.isEmpty()) {
				queue.notify();
				return queue.remove(0);
			} else {
				return null; // this means that queue is empty and closed
			}
		}
	}
	
	public void putItem(Email email) throws IllegalStateException {
		synchronized (queue) {
			while (queue.size() >= maxSize && !isClosed) {
				try {
					queue.wait();
				} catch (InterruptedException ignore) { }
			}
			
			if (isClosed)
				throw new IllegalStateException("queue is closed");
			
			if (queue.size() < maxSize) {
				queue.add(email);
				queue.notify();
			} else {
				// unreachable
			}
		}
	}
	
	public void close() {
		synchronized (queue) {
			isClosed = true;
		}
	}
	
	public boolean isClosed() {
		return isClosed;
	}
	
}
